#coding:utf-8

import logging
import sys
import md5
import time
import Image
import datetime
import decimal

decimal.getcontext().prec = 11
decimal.getcontext().rounding = decimal.ROUND_UP


def encode(u):
    """
    >>> encode('a')
    'a'
    """
    if isinstance(u, unicode):
        try:
            u = u.encode('utf-8')
        except:
            u = u.encode('ascii')
    return u


def decode(s):
    if isinstance(s, str):
        s = s.decode('utf-8')
    return s


def md5hash(src):
    if isinstance(src, unicode):
        return md5.new(src.encode("utf-8")).hexdigest()
    else:
        return md5.new(src).hexdigest()


def fen2yuan(fen):
    """
    >>> fen2yuan(100)
    '1.00'
    """
    f = decimal.Decimal(fen)
    y = f / decimal.Decimal(100)
    return str(y.quantize(decimal.Decimal('1.00')))


def yuan2fen(yuan):
    """
    >>> yuan2fen('1.00')
    100
    """
    y = decimal.Decimal(yuan)
    f = y * decimal.Decimal(100)
    return int(f.to_integral_value())


def get_score():
    return int(9999999999 - time.time())


def getLogger(name, logfile, debug=True):
    level = debug and logging.DEBUG or logging.ERROR
    formatter = logging.Formatter(u'%(name)-12s %(asctime)s %(levelname)-8s %(message)s', '%a, %d %b %Y %H:%M:%S', )
    logger = logging.getLogger(name)
    logger.setLevel(level)
    file_handler = logging.FileHandler(logfile)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    if level == logging.DEBUG:
        stream_handler = logging.StreamHandler(sys.stderr)
        logger.addHandler(stream_handler)
    return logger


def resize_img(img_path, out_path, new_width):
    #读取图像
    im = Image.open(img_path)
    #获得图像的宽度和高度
    width, height = im.size
    #计算高宽比
    ratio = 1.0 * height / width
    #计算新的高度
    new_height = int(new_width * ratio)
    new_size = (new_width, new_height)
    #插值缩放图像，
    out = im.resize(new_size, Image.ANTIALIAS)
    #保存图像
    out.save(out_path)


def thumb_img(srcfile, destfile, w, h):
    def get_region(im):
        width, height = im.size
        if width == height:
            region = im
        else:
            if width > height:
                delta = (width - height) / 2
                box = (delta, 0, delta + height, height)
            else:
                delta = (height - width) / 2
                box = (0, delta, width, delta + width)
            region = im.crop(box)
        return region

    img = get_region(Image.open(srcfile))
    img.thumbnail((w, h), resample=1)
    img.save(destfile)


def convtime(ctime):
    """
    >>> type(convtime('2012-01-14 00:00:00'))
    <type 'unicode'>
    >>> convtime('')
    ''
    """
    if not ctime:
        return ''
    cdate = datetime.datetime.strptime(ctime, '%Y-%m-%d %H:%M:%S')
    nowdate = datetime.datetime.now()
    dt = nowdate - cdate
    secs = dt.total_seconds()

    if secs < 60:
        return u"刚刚"
    minute = int(secs / 60)
    if minute >= 1 and minute < 60:
        return u"%s分钟前" % minute

    hours = int(secs / (60 * 60))
    if hours >= 1 and hours < 24:
        return u"%s小时前" % hours

    days = int(secs / (60 * 60 * 24))
    if days >= 1 and days < 31:
        return u"%s天前" % days

    months = int(secs / (60 * 60 * 24 * 30))
    if months >= 1 and months < 12:
        return u"%s月前" % months

    years = int(secs / (60 * 60 * 24 * 365))
    return u"%s年前" % years


def fmt_second(time_total):
    """
    >>> fmt_second(100)
    '00:01:40'
    """

    def _ck(t):
        return t < 10 and "0%s" % t or t

    times = int(time_total)
    h = times / 3600
    m = times % 3600 / 60
    s = times % 3600 % 60
    return "%s:%s:%s" % (_ck(h), _ck(m), _ck(s))


def rtitle(val, wd=20):
    if not val:
        return
    if len(val) >= wd:
        return val[0:(wd - 1)] + '...'
    return val + '...'


def gen_numid():
    times = str(time.time())
    uid = times.replace('\.', '')
    return uid[0:10]

def get_currtime():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def get_currdate():
    return datetime.datetime.now().strftime("%Y-%m-%d")

if __name__ == '__main__':
    import doctest
    doctest.testmod()